package com.xg.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xg.frame.log.annotation.LogAnnotation;
import com.xg.sys.entity.SysMenu;
import com.xg.sys.entity.SysRoleMenu;
import com.xg.sys.service.SysMenuService;
import com.xg.sys.service.SysRoleMenuService;
import com.xg.sys.vo.SysMenuVO;
import com.xg.sys.vo.TreeVO;
import com.xg.frame.constant.SysConstant;
import com.xg.frame.constant.UrlConstant;
import com.xg.frame.entity.R;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tzt
 * @date Created in 2021/8/13 12:04
 * @description：菜单管理
 * @modified By：
 */
@Controller
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/menu")
public class MenuController {
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @GetMapping
    public String index(Model model) throws Exception {
        //获取当前登录用户菜单（树）
        model.addAttribute("treeList", sysMenuService.treeAll());
        return "/sys/menu/list";
    }

    @ResponseBody
    @GetMapping("/{id}")
    public R<TreeVO> getById(@PathVariable Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        SysMenuVO sysMenuVO = new SysMenuVO();
        BeanUtils.copyProperties(sysMenu, sysMenuVO);
        return R.ok().info(sysMenuVO);
    }

    @LogAnnotation(module = UrlConstant.sysCenter, describe = "菜单新增修改")
    @RequiresPermissions("menu:save")
    @PostMapping("/save")
    public String save(@NotNull SysMenuVO vo, Model model) throws Exception {
        SysMenu menu = new SysMenu();
        BeanUtils.copyProperties(vo, menu);
        boolean save;
        if (vo.getId() == null) {
            final SysMenu parent = sysMenuService.getById(menu.getParentId());
            if (parent != null && SysConstant.MENU_TYPE_BUTTON.equals(parent.getType())) {
                //TODO 上级菜单不能为按钮
            }
            save = sysMenuService.save(menu);
        } else {
            save = sysMenuService.updateById(menu);
        }
        return index(model);
    }

    @LogAnnotation(module = UrlConstant.sysCenter, describe = "菜单删除")
    @RequiresPermissions("menu:del")
    @GetMapping("/del")
    @ResponseBody
    public R del(@NotNull Long id) {
        List<SysMenu> menuList = sysMenuService.getByParentId(id);
        if (CollectionUtils.isNotEmpty(menuList)) {
            return R.error().message("存在子菜单,请先删除子菜单!");
        }
        boolean result = sysMenuService.removeById(id);
        if (result) {
            sysRoleMenuService.remove(
                    new LambdaQueryWrapper<SysRoleMenu>()
                            .eq(SysRoleMenu::getMenuId, id)
            );
        }
        return result ? R.ok() : R.error();
    }

    @GetMapping("/query")
    @ResponseBody
    public R query(Long roleId) throws Exception {
        List<SysMenu> allList = sysMenuService.list();
        //获取菜单列表
        List<SysMenu> menuList = sysMenuService.getByRoleId(roleId);
        List<Long> menuIdList = menuList.stream().map(SysMenu::getId).collect(Collectors.toList());
        List<TreeVO> vos = TreeVO.toTree(allList, menuIdList);
        return R.ok().info(vos);
    }

}
